#ifndef TEXTEDITOR_H
#define TEXTEDITOR_H

#include <QWidget>
#include <QTextEdit>
#include <QToolBar>
#include <QAction>
#include <QVBoxLayout>
#include <QLabel>
#include <QSpinBox>
#include <QTextTable>
#include <QTextTableCell>
#include <QFrame>
#include "resizableimagetextedit.h"

#define DEFAULT_ROW_HEIGHT_MM 7.9    // 默认行高（毫米）
#define DEFAULT_COLUMN_WIDTH_MM 26.0 // 默认列宽（毫米）

class TextEditor : public QWidget
{
    Q_OBJECT

public:
    TextEditor(QWidget *parent = nullptr);
    ~TextEditor();
    bool exportToImage(const QString &outputPath,
                          const QString &imageFormat = "PNG",
                          const QColor &backgroundColor = Qt::white,
                          int dpi = 96,
                          double scaleFactor = 1.0);

private slots:
    void alignLeft();
    void alignCenter();
    void alignRight();
    void insertImage();
    void insertTable();
    void applyTableResize();
    void updateTableResizeControls();
//    void exportToHtml();  // 新增：导出HTML
//    void importFromHtml(); // 新增：导入HTML


private:
    struct ImageInfo
    {
        int lineNumber;  // 使用总行数作为图片起始行号
        int width;
        int height;
        QString imagePath;
    };

    struct ParsedTableInfo {
        int startLineNumber;                    // 表格起始行号
        int rows;                              // 行数
        int columns;                           // 列数
        QVector<double> rowHeights;            // 行高（毫米）
        QVector<double> columnWidths;          // 列宽（毫米）
        QVector<QVector<QString>> cellContents; // 单元格内容 [row][col]
    };

    void displayParsedContent(const QString &plainText,
                                 const QVector<ImageInfo> &imageList,
                                 const QVector<ParsedTableInfo> &tableList);
    void insertImageAtCursor(QTextCursor &cursor, const ImageInfo &imageInfo);
        void insertTableAtCursor(QTextCursor &cursor, const ParsedTableInfo &tableInfo);
        int mmToPixels(double mm);
        QTextCursor moveToLineStart(QTextDocument *document, int lineNumber);
    bool saveRichTextToHtmlWithBase64(QTextEdit* textEdit, const QString& filePath);
    QString parseHtmlWithImagesAndTables(const QString &htmlContent,
                                           const QString &outputImagePath,
                                           QVector<ImageInfo> &imageList,
                                           QVector<ParsedTableInfo> &tableList,
                                           int lineHeight = 20);

    void setupToolbar();
    void setupToolbarActions();
    void setupTableResizeControls();

    // 表格相关辅助方法
    QTextTable *getSelectedTable();
    int getCurrentTableRow();
    int getCurrentTableColumn();
    int calculateCurrentRowHeight(const QTextTableCell &cell);
    bool hasTableSelection();
    // ... existing code ...
    void onDocumentContentsChanged();
    void cleanupDeletedTables();

private:
        // ... existing methods ...

        QString generateHtmlWithTableDimensions(bool useCustomDimensions);
        QString convertTableToHtmlWithDimensions(QTextTable *table, bool useCustomDimensions);
        QString convertBlockToHtml(const QTextBlock &block, bool addParagraph = true);
private:
    // 主要组件
    QFrame *editorFrame;              // 包装容器
    ResizableImageTextEdit *textEdit;
    QToolBar *toolBar;

    // 工具栏动作
    QAction *leftAlignAction;
    QAction *centerAlignAction;
    QAction *rightAlignAction;
    QAction *insertImageAction;
    QAction *insertTableAction;

    // 表格调整控件
    QWidget *tableResizeWidget;
    QLabel *columnWidthLabel;
//    QSpinBox *columnWidthSpinBox;
    QLabel *rowHeightLabel;
//    QSpinBox *rowHeightSpinBox;
    QDoubleSpinBox *columnWidthSpinBox;
    QDoubleSpinBox *rowHeightSpinBox;

    QAction *exportHtmlAction;  // 新增：导出HTML动作
    QAction *importHtmlAction;  // 新增：导入HTML动作

    double m_dpi;

    // 在TextEditor类中添加表格信息结构体
    struct TableInfo {
        QVector<double> columnWidths;  // 列宽（像素）
        QVector<double> rowHeights;    // 行高（像素）
        int rows;
        int columns;

        TableInfo() : rows(0), columns(0) {}

        TableInfo(int r, int c) : rows(r), columns(c) {
            columnWidths.resize(c);
            rowHeights.resize(r);
            // 设置默认值
            for (int i = 0; i < c; i++) {
                columnWidths[i] = 26.0; // 26mm转像素
            }
            for (int i = 0; i < r; i++) {
                rowHeights[i] = 7.9; // 7.9mm转像素
            }
        }
    };



    // 在TextEditor类中添加表格映射
    QMap<QTextTable*, TableInfo> tableInfoMap;

private:
    // ... existing members ...

    // 存储用户自定义的表格尺寸
    QMap<QTextTable*, QList<double>> customRowHeights;    // 自定义行高
    QMap<QTextTable*, QList<double>> customColumnWidths;  // 自定义列宽

    // 表格尺寸相关方法
    void storeCustomTableDimensions(QTextTable *table, const QList<double> &rowHeights, const QList<double> &colWidths);
    QList<double> getTableRowHeights(QTextTable *table, bool useCustom = true);
    QList<double> getTableColumnWidths(QTextTable *table, bool useCustom = true);
};

#endif // TEXTEDITOR_H
